<?php

namespace app\admin\model;

use think\Model;
use think\Db;


class Order extends Model
{
    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'start_time_text',
        'end_time_text',
        'status_text'
    ];

    // 订单状态
    const STATUS_CANCELLED = 0; // 取消
    const STATUS_PENDING = 1;   // 待开始
    const STATUS_PROGRESS = 2;  // 进行中
    const STATUS_COMPLETED = 3; // 已结束

    public function getStatusList()
    {
        return ['0' => '已取消', '1' => '待开始', '2' => '进行中', '3' => '已结束'];
    }


    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['start_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['end_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function project()
    {
        return $this->belongsTo('Project', 'project_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

//    public function getHandlerNameAttr($value,$data)
//    {
//        if (empty($value)) {
//            return '无打手';
//        }
//
//        // 将ID转换为名称
//        $ids = explode(',', $value);
//        $names = \think\Db::name('handler')
//            ->where('id', 'in', $ids)
//            ->column('name');
//
//        return implode('、', $names) ?: '未知打手';
//    }

    // 获取打手信息（带样式）
    public function getHandlersBadgeAttr($value, $data)
    {
        if (empty($data['handler_ids'])) {
            return '<span class="label label-default">无打手</span>';
        }

        $handlerIds = explode(',', $data['handler_ids']);
        $handlers = \think\Db::name('handler')
            ->where('id', 'in', $handlerIds)
            ->column('name');

        $badges = [];
        foreach ($handlers as $name) {
            $badges[] = '<span class="label label-primary">' . $name . '</span>';
        }

        return implode(' ', $badges);
    }

    /**
     * 生成订单编号
     */
    public static function generateOrderSn()
    {
        return "DD" . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
    }

    /**
     * 获取用户等级折扣
     */
    public static function getUserLevelDiscount($userId)
    {
        $user = Db::name('user')->where('id', $userId)->find();
        if ($user && $user['level_id'] > 0) {
            $level = Db::name('user_level')->where('id', $user['level_id'])->find();
            return $level ? $level['discount'] : 1.00;
        }
        return 1.00;
    }

    /**
     * 获取打手抽成比例
     */
    public static function getHandlerCommissionRate($handlerId)
    {
        $handler = Db::name('handler')->where('id', $handlerId)->find();
        if ($handler && $handler['level_id'] > 0) {
            $level = Db::name('handler_level')->where('id', $handler['level_id'])->find();
            return $level ? $level['commission_rate'] : 0.00;
        }
        return 0.00;
    }

    /**
     * 订单退款逻辑
     */
    public function refundOrder($order)
    {
        // 获取用户信息并锁定记录
        $user = \think\Db::name('user')->where('id', $order->user_id)->lock(true)->find();
        if (!$user) {
            throw new \Exception('用户不存在，无法退款');
        }

        // 退款金额
        $refundAmount = $order->total_amount;

        // 更新用户余额
        $newBalance = bcadd($user['money'], $refundAmount, 2);
        $updateResult = \think\Db::name('user')
            ->where('id', $order->user_id)
            ->update([
                'money' => $newBalance,
                'updatetime' => time()
            ]);

        if ($updateResult === false) {
            throw new \Exception('退款失败：更新用户余额失败');
        }

        // 记录退款资金流水
        $moneyLogData = [
            'user_id' => $order->user_id,
            'money' => $refundAmount,
            'before' => $user['money'],
            'after' => $newBalance,
            'memo' => '订单取消退款：' . $order->order_sn . '，退款金额：¥' . $refundAmount,
            'createtime' => time()
        ];

        $moneyLogResult = \think\Db::name('user_money_log')->insert($moneyLogData);
        if (!$moneyLogResult) {
            throw new \Exception('退款失败：记录资金流水失败');
        }
        $order->save();

    }

    /**
     * 完成订单结算
     */
    public function completeOrder($order)
    {
        if (empty($order->handler_ids)) {
            throw new \Exception('订单未分配打手');
        }

        $handlerIds = is_array($order->handler_ids) ? $order->handler_ids : explode(',', $order->handler_ids);


        $updateResult = Db::name('handler')
            ->where('id', 'in', $handlerIds)
            ->update([
                'custom' => 0
            ]);
        // 处理每个打手的结算
        foreach ($handlerIds as $handlerId) {
            $this->settleHandler($order, $handlerId);
        }

        return true;
    }

    /**
     * 打手结算
     */
    private function settleHandler($order, $handlerId)
    {
        // 获取打手抽成比例
        $commissionRate = self::getHandlerCommissionRate($handlerId);

        // 计算实际到手金额（扣除平台抽成）
        $commissionAmount = bcmul($order->handler_amount, bcdiv($commissionRate, 100, 4), 2);
        $actualAmount = bcsub($order->handler_amount, $commissionAmount, 2);

        // 先获取当前的余额
        $handlerBalance = Db::name('handler')
            ->where('id', $handlerId)
            ->field('id, money,total_income')->find();

        $currentBalance = $handlerBalance['money'] ?: '0.00';

        // 计算新的余额
        $newBalance = bcadd($currentBalance, $actualAmount, 2);

        // 更新打手未结算收入
        $updateResult = Db::name('handler')
            ->where('id', $handlerId)
            ->update([
                'money' => $newBalance,
                'total_income' => bcadd($handlerBalance['total_income'], $actualAmount, 2),
                'updatetime' => time()
            ]);

        if ($updateResult === false) {
            throw new \Exception('更新打手余额失败');
        }

        // 记录资金流水
        $moneyLogData = [
            'handler_id' => $handlerId,
            'money' => $actualAmount,
            'before' => $currentBalance,
            'after' => $newBalance,
            'memo' => "订单 {$order->order_sn} 结算，抽成{$commissionRate}%",
            'createtime' => time()
        ];

        $moneyLogResult = Db::name('handler_money_log')->insert($moneyLogData);
        if (!$moneyLogResult) {
            throw new \Exception('记录资金流水失败');
        }

        return true;
    }

}
